import { Options, Vue } from 'vue-class-component'
import store from '@/store'
import navigator from '@/components/common/navigator.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { saveBackTestReport } from '@/api/develop'

interface iSheet {
  conditionSheetId: string
  conditionSheetName: string
  onState: number
  authorId: string
  createTime: Date
  updateTime: Date
}

interface iCondition {
  conditionId: string
  conditionName: string
  updateTime: Date
  conditionParameter: string
  orderType: string
}

@Options({
  components: {
    navigator
  }
})

export default class conditionSheet extends Vue {
  sheets: iSheet[] = []
  openingSheets: iSheet[] = []
  displayingSheets: iSheet[] = []
  conditions: iCondition[] = []
  listConditions = []
  // sheets = [
  //   {
  //     conditionSheetId: '1',
  //     conditionSheetName: '条件单1',
  //     onState: 0,
  //     authorId: '1',
  //     createTime: '2021-06-15T17:59:45.000+00:00',
  //     updateTime: '2021-06-21T17:59:52.000+00:00'
  //   },
  //   {
  //     conditionSheetId: '3',
  //     conditionSheetName: '条件单3',
  //     onState: 1,
  //     authorId: '1',
  //     createTime: '2021-06-01T18:00:30.000+00:00',
  //     updateTime: '2021-06-21T18:00:34.000+00:00'
  //   }
  // ]
  //
  // openingSheets = [
  //   {
  //     conditionSheetId: '1',
  //     conditionSheetName: '条件单1',
  //     onState: 0,
  //     authorId: '1',
  //     createTime: '2021-06-15T17:59:45.000+00:00',
  //     updateTime: '2021-06-21T17:59:52.000+00:00'
  //   },
  //   {
  //     conditionSheetId: '3',
  //     conditionSheetName: '条件单3',
  //     onState: 1,
  //     authorId: '1',
  //     createTime: '2021-06-01T18:00:30.000+00:00',
  //     updateTime: '2021-06-21T18:00:34.000+00:00'
  //   }
  // ]
  //
  // displayingSheets = [
  //   {
  //     conditionSheetId: '1',
  //     conditionSheetName: '条件单1',
  //     onState: 0,
  //     authorId: '1',
  //     createTime: '2021-06-15T17:59:45.000+00:00',
  //     updateTime: '2021-06-21T17:59:52.000+00:00'
  //   },
  //   {
  //     conditionSheetId: '3',
  //     conditionSheetName: '条件单3',
  //     onState: 1,
  //     authorId: '1',
  //     createTime: '2021-06-01T18:00:30.000+00:00',
  //     updateTime: '2021-06-21T18:00:34.000+00:00'
  //   }
  // ]

  id = ''
  openingSheet: iSheet = {
    conditionSheetId: '',
    conditionSheetName: '',
    onState: 0,
    authorId: '',
    createTime: null,
    updateTime: null
  }

  selectedSheetType = '所有条件单'
  elMainType = '初始界面'
  changingSheetName = false
  openingSheetName = ''
  selectedOrderType = '买入'
  buyPercent = '0'
  sellPercent = '0'
  necessaryCondition: iCondition = null
  backtestVisable = false
  backtestForm = {
    stock: '',
    time: ''
  }

  backtestFormLabelWidth = '120px'
  backtestResult = null
  yield = ''

  shortcuts = [{
    text: '最近一周',
    value: (() => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    })()
  }, {
    text: '最近一个月',
    value: (() => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    })()
  }, {
    text: '最近三个月',
    value: (() => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    })()
  }]

  applyForShelfVisable = false
  commodity = null
  shelfForm = {
    commodityName: '',
    commodityDescription: '',
    commodityPrice: 0
  }

  reportList = []
  stockList = []

  mounted () {
    this.id = store.state.u.userId
    store.dispatch('getSheets', this.id)
      .then(response => {
        console.log('connect success')
        this.sheets = response.data.data
        this.displayingSheets = this.sheets.slice()
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
    store.dispatch('getListConditions')
      .then(response => {
        this.listConditions = response.data.data
        for (let i = 0; i < this.listConditions.length; ++i) {
          if (this.listConditions[i].conditionName === '仓位') {
            this.necessaryCondition = JSON.parse(JSON.stringify(this.listConditions[i]))
            this.listConditions.splice(i, 1)
            break
          }
        }
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
    store.dispatch('getAllStocks')
      .then(response => {
        console.log('connect success')
        this.stockList = response.data.data
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  siftSheet () {
    let type
    if (this.selectedSheetType === '已上架条件单') {
      type = 1
    } else if (this.selectedSheetType === '未上架条件单') {
      type = 0
    } else if (this.selectedSheetType === '审核中条件单') {
      type = 2
    } else {
      this.displayingSheets.splice(0)
      for (let i = 0; i < this.sheets.length; ++i) {
        this.displayingSheets.push(this.sheets[i])
      }
      return
    }
    this.displayingSheets.splice(0)
    for (let i = 0; i < this.sheets.length; ++i) {
      if (this.sheets[i].onState === type) {
        this.displayingSheets.push(this.sheets[i])
      }
    }
  }

  openSheet (sheet) {
    this.openingSheet = JSON.parse(JSON.stringify(sheet))
    this.openingSheetName = sheet.conditionSheetName
    let flag = true
    for (let i = 0; i < this.openingSheets.length; ++i) {
      if (this.openingSheets[i].conditionSheetId === sheet.conditionSheetId) {
        flag = false
        break
      }
    }
    if (flag) {
      this.openingSheets.unshift(sheet)
    }
    store.dispatch('getConditions', sheet.conditionSheetId)
      .then(response => {
        console.log('connect success')
        this.conditions = response.data.data
        for (let i = 0; i < this.conditions.length; ++i) {
          if (this.conditions[i].conditionName === '仓位') {
            if (this.conditions[i].orderType === '买入') {
              this.buyPercent = this.conditions[i].conditionParameter
            } else {
              this.sellPercent = this.conditions[i].conditionParameter
            }
          }
        }
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
    this.elMainType = '条件单详情'
  }

  closeSheet (index) {
    if (this.openingSheet.conditionSheetId === this.openingSheets[index].conditionSheetId) {
      this.elMainType = '初始界面'
    }
    this.openingSheets.splice(index, 1)
  }

  startChangingSheetName () {
    this.changingSheetName = true
  }

  changeSheetName () {
    this.openingSheet.conditionSheetName = this.openingSheetName
    store.dispatch('changeSheetName', this.openingSheet)
      .then(response => {
        console.log('connect success')
        console.log('修改条件单名称成功')
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
    this.changingSheetName = false
  }

  startCreateSheet () {
    this.changingSheetName = false
    this.elMainType = '新建条件单'
    this.selectedOrderType = '买入'
    this.openingSheet.conditionSheetName = '新建条件单'
    this.openingSheet.authorId = this.id
    this.openingSheetName = '新建条件单'
    this.conditions.splice(0)
    const buyCondition = JSON.parse(JSON.stringify(this.necessaryCondition))
    buyCondition.conditionParameter = '0'
    buyCondition.orderType = '买入'
    const sellCondition = JSON.parse(JSON.stringify(this.necessaryCondition))
    sellCondition.conditionParameter = '0'
    sellCondition.orderType = '卖出'
    this.conditions.push(buyCondition)
    this.conditions.push(sellCondition)
  }

  addCondition (condition) {
    condition = JSON.parse(JSON.stringify(condition))
    condition.conditionParameter = ''
    condition.orderType = this.selectedOrderType
    for (let i = 0; i < this.conditions.length; ++i) {
      if (this.conditions[i].orderType === this.selectedOrderType && this.conditions[i].conditionId === condition.conditionId) {
        return
      }
    }
    this.conditions.push(condition)
  }

  deleteCondition (index) {
    this.conditions.splice(index, 1)
  }

  createSheet () {
    if (this.conditions.length <= 2) {
      ElMessage.warning({
        message: '条件单不能为空',
        type: 'warning'
      })
      return
    }
    this.openingSheet.conditionSheetName = this.openingSheetName
    const data = {
      authorId: this.id,
      conditionSheetName: this.openingSheet.conditionSheetName,
      conditions: this.conditions
    }
    console.log(data)
    store.dispatch('createSheet', data)
      .then(response => {
        console.log('connect success')
        ElMessageBox.alert('条件单创建成功', '', {
          confirmButtonText: '确定',
          callback: action => {
            location.reload()
          }
        })
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  deleteSheet (index) {
    store.dispatch('deleteSheet', this.displayingSheets[index].conditionSheetId)
      .then(response => {
        console.log('connect success')
        for (let i = 0; i < this.sheets.length; ++i) {
          if (this.sheets[i].conditionSheetId === this.displayingSheets[index].conditionSheetId) {
            this.openingSheets.splice(i, 1)
          }
        }
        for (let i = 0; i < this.openingSheets.length; ++i) {
          if (this.openingSheets[i].conditionSheetId === this.displayingSheets[index].conditionSheetId) {
            this.openingSheets.splice(i, 1)
          }
        }
        this.displayingSheets.splice(index, 1)
        console.log('删除条件单成功')
        ElMessageBox.alert('删除条件单成功', '', {
          confirmButtonText: '确定'
        })
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  backtest () {
    this.backtestVisable = false
    const data = {
      conditionSheetId: this.openingSheet.conditionSheetId,
      backTestStock: this.backtestForm.stock,
      startTime: this.backtestForm.time[0],
      endTime: this.backtestForm.time[1]
    }
    this.elMainType = '回测图表展示'
    this.yield = ''
    store.dispatch('backtest', data)
      .then(response => {
        console.log('connect success')
        this.backtestResult = response.data.data
        this.yield = Number(this.backtestResult.yield * 100).toFixed(1)
        console.log(this.backtestResult)
        const data2 = []
        for (const competeItem of this.backtestResult.singleBackTestResultVOS) {
          // console.log(competeItem.day)
          const dp = [
            competeItem.day,
            competeItem.property.toFixed(1)
          ]
          data2.push({ value: dp })
        }
        const data = []
        const myChart = echarts.init(document.getElementById('nowEcharts'))
        const option = {
          title: {
            text: '回测资产走势'
          },
          tooltip: {
            trigger: 'axis',
            formatter: function (params) {
              params = params[0]
              return params.value[0] + ': ' + params.value[1]
            },
            axisPointer: {
              animation: false
            }
          },
          xAxis: {
            name: '时间',
            type: 'time'
            // min: this.competeData[0].day,
            // max: this.competeData[length - 1].day
          },
          yAxis: {
            type: 'value',
            min: function (value) {
              return Math.floor(value.min - 1000)
            },
            max: function (value) {
              return Math.ceil(value.max + 1000)
            },
            boundaryGap: [0, '100%']
          },
          series: [{
            type: 'line',
            showSymbol: false,
            hoverAnimation: false,
            smooth: true,
            data: data
          }]
        }
        myChart.setOption(option)
        setInterval(function () {
          if (data2 === null) {
          } else {
            for (let i = 0; i < 20; i++) {
              data.push(data2.shift())
              if (!data == null) {
                data.shift()
              }
            }
            myChart.setOption(option)
          }
        }, 500)
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  saveBackTestReport () {
    const data = {
      conditionSheetId: this.openingSheet.conditionSheetId,
      backTestStock: this.backtestForm.stock,
      startTime: this.backtestForm.time[0],
      endTime: this.backtestForm.time[1],
      backTestYield: this.backtestResult.yield
    }
    store.dispatch('saveBackTestReport', data)
      .then(response => {
        ElMessageBox.alert('成功保存回测报告', '', {
          confirmButtonText: '确定'
        })
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  applyforShelf () {
    this.applyForShelfVisable = false
    const data = {
      conditionSheetId: this.openingSheet.conditionSheetId,
      commodityName: this.shelfForm.commodityName,
      commodityDescription: this.shelfForm.commodityDescription,
      commodityPrice: this.shelfForm.commodityPrice,
      authorId: this.id
    }
    store.dispatch('applyForShelf', data)
      .then(response => {
        if (response.data.data.code === 500) {
          ElMessageBox.alert(response.data.data.message, '', {
            confirmButtonText: '确定'
          })
          return
        }
        ElMessageBox.alert('上架申请已提交，请等待后台审核通过', '', {
          confirmButtonText: '确定'
        })
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  }

  showReportList () {
    store.dispatch('getReportList', this.id)
      .then(response => {
        this.reportList = response.data.data
        for (let i = 0; i < this.reportList.length; ++i) {
          this.reportList[i].yield = this.reportList[i].backTestYield.toFixed(4) * 100 + '%'
        }
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
    this.elMainType = '回测报告列表'
  }

  showReport (row) {
    console.log(row)
  }
}
